import time
import re
import uuid
import os
from datetime import datetime

def date2timestamp(date_str):
    """将日期字符串转换为时间戳"""
    try:
        dt = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
        return int(time.mktime(dt.timetuple()))
    except:
        return int(time.time())

def replace_double_slash(url):
    """替换URL中的双斜杠"""
    return re.sub(r'(?<!:)//+', '/', url)

def generate_order_no():
    """生成订单号"""
    import random
    import string
    timestamp = str(int(time.time()))
    random_str = ''.join(random.choices(string.digits, k=6))
    return f"HXG{timestamp}{random_str}"

def generate_unique_filename(original_filename):
    """生成唯一文件名"""
    ext = os.path.splitext(original_filename)[1]
    unique_name = str(uuid.uuid4())
    return f"{unique_name}{ext}"

def validate_image_file(file):
    """验证图片文件"""
    allowed_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp']
    max_size = 5 * 1024 * 1024  # 5MB
    
    if not file:
        return False, "文件不能为空"
    
    # 检查文件大小
    if file.size > max_size:
        return False, "文件大小不能超过5MB"
    
    # 检查文件扩展名
    ext = os.path.splitext(file.name)[1].lower()
    if ext not in allowed_extensions:
        return False, f"不支持的文件格式，支持格式：{', '.join(allowed_extensions)}"
    
    return True, "验证通过"

def format_price(price):
    """格式化价格"""
    return f"{float(price):.2f}"

def validate_phone(phone):
    """验证手机号"""
    pattern = r'^1[3-9]\d{9}$'
    return bool(re.match(pattern, phone))

def mask_phone(phone):
    """手机号脱敏"""
    if len(phone) == 11:
        return phone[:3] + '****' + phone[7:]
    return phone

def get_client_ip(request):
    """获取客户端IP地址"""
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

def paginate_queryset(queryset, page, page_size=20):
    """分页查询集"""
    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    
    paginator = Paginator(queryset, page_size)
    
    try:
        page_obj = paginator.page(page)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)
    
    return {
        'results': list(page_obj),
        'count': paginator.count,
        'num_pages': paginator.num_pages,
        'current_page': page_obj.number,
        'has_next': page_obj.has_next(),
        'has_previous': page_obj.has_previous(),
        'next_page_number': page_obj.next_page_number() if page_obj.has_next() else None,
        'previous_page_number': page_obj.previous_page_number() if page_obj.has_previous() else None,
    }
